package com.qinhailin.portal.dbm.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.kit.PropKit;
import com.qinhailin.common.util.HttpUtil;
import com.qinhailin.portal.dbm.model.DTContact;
import com.qinhailin.portal.dbm.model.DTCustomer;
import com.qinhailin.portal.dbm.po.Message;
//import com.qinhailin.portal.dbm.util.com.zjiecode.wxpusher.client.bean.Message;
import com.qinhailin.portal.dbm.util.com.zjiecode.wxpusher.client.bean.Result;


public class WXPusherServiceImpl{

	private String url = "http://wxpusher.zjiecode.com/api/send/message/?appToken=" + PropKit.use("config.properties").get("app_token") + "&content={1}&uid={2}";
	
	public Result send(String msg, String uid) {
		try {
			msg = URLEncoder.encode(msg, "utf-8");
		} catch (UnsupportedEncodingException exception) {
			Logger.getLogger(WXPusherServiceImpl.class).error(exception);
		}
		String rs = HttpUtil.get(url.replace("{2}", uid).replace("{1}", msg));		// 先2后1以免1里有类似字符 至于2里是不会有{1}这样的字符的
		//DBM.getInstance().contactlogService.save(new DTContactLog().setXType(2).setXMessage(msg).setXUIDe(uid).setXResult(rs).setXDateTime(DateUtil.getCurrentTimestamp()));
		Result r = null;
		if(rs != null && rs.length() > 0) {
			r = JSONObject.parseObject(rs, Result.class);
		}
		
		return r;
	}

	public Result send(String msg, List<String> uid) {
		Result rs = null;
		if(uid != null) {
			for(String u : uid){
				rs = this.send(msg, u);
			}
		}
		return rs;
	}
	
	@Inject
	DTContactServiceImpl contactService;
	//@Inject
	//DTCustomerContactServiceImpl customerContactService;
	
	public Result send(String msg, DTCustomer customer) {
		Result rs = null;
		List<DTContact> cs = contactService.list(customer.getSID());
		if(cs != null) {
			for(DTContact c : cs) {
				this.send(msg, c.getXWXOpenID());
			}
		}
		return rs;
	}

	public Result send(Message msg) {
		return this.send(msg.getXMsg(), msg.getXWXOpenID());
	}

}
